from flask import Flask, render_template, request
import random
import requests

app = Flask(__name__)

# 生成前区号码的函数
def generate_numbers():
    sections = [(1, 12), (13, 24), (25, 35)]
    ratios_options = [[2, 0, 3], [2, 1, 2], [2, 2, 1], [1, 2, 2], [1, 1, 3], [1, 3, 1], [3, 1, 1], [0, 3, 2],
                      [0, 2, 3], [2, 3, 0], [3, 2, 0]]
    ratios_options_weights = [0.04, 0.13, 0.14, 0.13, 0.06, 0.05, 0.10, 0.06, 0.05, 0.03, 0.05]
    ratios = random.choices(ratios_options, weights=ratios_options_weights, k=1)[0]

    picked_numbers = []
    total_sum = 0

    even_ratio = [(2, 3), (3, 2), (4, 1), (1, 4), (0, 5), (5, 0)]
    weights = [0.28, 0.31, 0.20, 0.13, 0.03, 0.05]
    odd_even_ratio = random.choices(even_ratio, weights=weights, k=1)[0]
    required_odds, required_evens = odd_even_ratio
    total_sum_list = [(30, 39), (40, 49), (50, 59),
                      (60, 69), (70, 79), (80, 89),
                      (90, 99), (100, 109), (110, 119),
                      (120, 129), (130, 139)]
    total_sum_weights = [0.02, 0.01, 0.08, 0.08, 0.14, 0.13, 0.18, 0.15, 0.15, 0.04, 0.02]
    total_sum_result = random.choices(total_sum_list, weights=total_sum_weights, k=1)[0]
    start, end = total_sum_result

    attempt = 0
    while not start <= total_sum <= end or len([num for num in picked_numbers if num % 2 != 0]) != required_odds or len(
            [num for num in picked_numbers if num % 2 == 0]) != required_evens:
        picked_numbers.clear()
        total_sum = 0

        if attempt == 1000:
            break

        for ratio, section in zip(ratios, sections):
            for _ in range(ratio):
                if len([num for num in picked_numbers if num % 2 != 0]) < required_odds and random.choice(
                        [True, False]):
                    num = random.choice([n for n in range(section[0], section[1] + 1) if n % 2 != 0])
                else:
                    num = random.choice([n for n in range(section[0], section[1] + 1) if n % 2 == 0])

                while num in picked_numbers:
                    num = random.choice([n for n in range(section[0], section[1] + 1) if
                                         n % 2 != 0]) if num % 2 != 0 else random.choice(
                        [n for n in range(section[0], section[1] + 1) if n % 2 == 0])

                picked_numbers.append(num)
                total_sum += num

        attempt += 1
    return picked_numbers, total_sum, ratios, odd_even_ratio

# 随机后区号码
def random_nums():
    small_number = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
    small_number_weight = [0.10, 0.09, 0.07, 0.06, 0.10, 0.11, 0.08, 0.07, 0.11, 0.08, 0.05, 0.08]

    first_number = random.choices(small_number, weights=small_number_weight, k=1)[0]

    updated_weights = [w / (1 - small_number_weight[small_number.index(first_number)]) for i, w in
                       enumerate(small_number_weight) if small_number[i] != first_number]
    updated_numbers = [n for n in small_number if n != first_number]

    second_number = random.choices(updated_numbers, weights=updated_weights, k=1)[0]

    return [first_number, second_number]

def fetch_and_convert_result():
    url = "https://webapi.sporttery.cn/gateway/lottery/getHistoryPageListV1.qry?gameNo=85&provinceId=0&pageSize=30&isVerify=1&pageNo=1"
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
    }

    response = requests.get(url, headers=headers)
    response.raise_for_status()

    data = response.json()

    first_result = data['value']['list'][0]['lotteryDrawResult']

    result_list = [int(num) for num in first_result.split()][:7]
    #print(result_list)
    return result_list

def has_consecutive_numbers(numbers):
    numbers.sort()
    for i in range(len(numbers) - 1):
        if numbers[i] + 1 == numbers[i + 1]:
            return True
    return False
def generate_results():
    all_results = []
    count = 0
    while count < 10:
        try:
            numbers, total_sum, ratios, odd_even_ratio = generate_numbers()
            has_numbers = has_consecutive_numbers(numbers)
            behind = random_nums()
            max_value = max(numbers)
            min_value = min(numbers)
            span = max_value - min_value

            set1 = set(fetch_and_convert_result())
            set2 = set(numbers)

            common_elements = set1.intersection(set2)
            repeatlist = [0, 1, 2]
            repeatlist_weight = [0.42, 0.48, 0.10]
            repeat = random.choices(repeatlist, weights=repeatlist_weight, k=1)[0]

            if len(common_elements) == repeat:
                if not has_numbers:
                    result = f"前区: {sorted(numbers)}, 后区: {sorted(behind)}"


                    all_results.append(result)
                    count +=1
        except Exception as e:
            pass
        #all_results[10]=fetch_and_convert_result()
    return all_results
@app.route('/', methods=['GET', 'POST'])
@app.route('/', methods=['GET', 'POST'])
def index():
    # 生成10组号码
    results = generate_results()
    # 获取最新一期的开奖号码
    latest_result = fetch_and_convert_result()
    # 将生成的号码和最新开奖号码传递给模板
    return render_template('index.html', results=results, latest_result=latest_result)
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)